import React, { useState, useEffect } from 'react';
import { TextArea, Button, Dialog, Mask, SpinLoading } from 'antd-mobile';
import { showErrorToast, showSuccessToast } from '@/utils/customToast';
const { aiCreate, aiCreatePrice } = $globalServicer('world')

import styles from './index.module'

/**
 * 角色卡/世界卡 智能创建组件
 */
const AiCreation = ({show, type, onResult}) => {
  const [visible, setVisible] = useState(false);
  const [maskVisible, setMaskVisible] = useState(false);  
  const [description, setDescription] = useState('');
  const [price, setPrice] = useState(null);

  useEffect(() => {
    // 获取智能创建消耗配置
    if (show) {
      aiCreatePrice().then(res => {
        setPrice(res.fixed_diamond_cost);
      }).catch(() => {
        showErrorToast('获取智能创建价格失败，请稍后再试');
      });
      setVisible(true);
    }
  }, [show])

  const showConfirm = () => {
    if (!description || description.length < 10) {
      showErrorToast('提示词过于简短，请输入至少10个字的提示词');
      return;
    }

    Dialog.confirm({
      content: `此操作将消耗 ${price} 梦匙，确定继续吗？`,
      cancelText: '取消',
      confirmText: '确定',
      onConfirm: () => {
        submitAiCreation();
      }
    })
  }

  const submitAiCreation = () => {
    // 这里可以添加AI创建逻辑
    console.log('智能创建逻辑执行');
    setMaskVisible(true);

    aiCreate({
      description: description,
      type
    }).then(res => {
      setMaskVisible(false);
      showSuccessToast('智能创建成功');
      onResult(res);
    }).catch(() => {
      showErrorToast('智能创建失败，请稍后再试');
    }).finally(() => {
      setMaskVisible(false);
    });
  }

  return visible && (
    <div className={styles.aiCreationWrapper}>
      <TextArea 
        className="text"
        rows={6}
        placeholder="输入提示词，例如：角色信息、故事背景等。"
        onChange={(val) => {
          setDescription(val);
        }} 
      />
      <Button className="submitButton" onClick={showConfirm}>使用 {price} 梦匙，智能创建</Button>
      <p className="tips">*AI将根据上方输入的提示词分析填写下列角色参数*</p>

      <Mask visible={maskVisible} className={styles.mask}>
        <SpinLoading color='primary' />
        <p>正在分析提示词</p>
      </Mask>
    </div>
  );
}

export default AiCreation;